package com.hqj.client.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqj.client.entity.Classify;
import com.hqj.client.mapper.ClassifyMapper;
import com.hqj.client.service.ClassifyService;
import com.hqj.common.ServiceException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ClassifyServiceImpl implements ClassifyService {
    @Resource
    private ClassifyMapper classifyMapper;

    @Override
    public int doInsertClassify(String name, Integer parentId, Integer type) {
        Classify classify = new Classify();
        classify.setName(name);
        classify.setParentId(parentId);
        classify.setIsDelete(0);
        classify.setType(type);
        int count = classifyMapper.insert(classify);
        if (count<1)
            throw new ServiceException("存入失败");
        return count;
    }

    @Override
    public List<Classify> doSelectPage(int page, int size) {
        QueryWrapper<Classify> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        Page<Classify> classifyPage = classifyMapper.selectPage(new Page<>(page,size),wrapper);
        if(classifyPage==null)
            throw new ServiceException("记录不存在");
        return classifyPage.getRecords();
    }

    @Override
    public int doDeleteClassify(Long id) {
        if (id<1)
            throw new IllegalArgumentException("id值无效");
        QueryWrapper<Classify> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        Classify selectOne = classifyMapper.selectOne(wrapper);
        if (selectOne.getIsDelete()==1)
            throw new ServiceException("该记录已经被删除了");
        selectOne.setIsDelete(1);
        int updateRecords = classifyMapper.updateById(selectOne);
        return updateRecords;
    }

    @Override
    public int doUpdateClassify(Classify classify) {
        if (classify.getId()<1)
            throw new IllegalArgumentException("id值无效");
        QueryWrapper<Classify> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0).eq("id",classify.getId());
        Classify selectOne = classifyMapper.selectOne(wrapper);
        if (selectOne==null)
            throw new ServiceException("该记录已经被删除");
        selectOne.setName(classify.getName());
        selectOne.setParentId(classify.getParentId());
        selectOne.setType(classify.getType());
        return classifyMapper.updateById(selectOne);
    }

    @Override
    public List<Classify> doSelectByName(String name) {
        QueryWrapper<Classify> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0).like("name",name);
        List<Classify> classifyList = classifyMapper.selectList(wrapper);
        for (Classify c:classifyList) {
            System.out.println(c);
        }
        return classifyList;
    }
}
